home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: news.sprintlink.net!eskimo!news
- From: mag@eskimo.com (mAg)
- Subject: Re: Pointers to structures
- X-Nntp-Posting-Host: tia1.eskimo.com
- Message-ID: <DKLDnH.96B@eskimo.com>
- Sender: news@eskimo.com (News User Id)
- Organization: *.*
- X-Newsreader: WinVN 0.93.10
- References: <4cc9r4$m26@armitage.cyberspace.com>
- Date: Wed, 3 Jan 1996 06:21:16 GMT
-
- In article <4cc9r4$m26@armitage.cyberspace.com> (2 Jan 1996 21:59:00 GMT), icarus@loomis
- says :
- >
- >I'm having trouble using a pointer to a struct. The idea is to have a
- >struct get filled by a function, which gets the address and everything
- >via function(struct type*). Very straightforward. However, if I try to
- >CHANGE anything in the struct, it just goes back when the function is
- >over. So, let's pretend this imaginary structure is what I'm using:
- >
- >struct st1 {
- > char *name;
- > int yadda;
- >};
- >
- >And the function is:
- >
- >fn1(struct st1 *st)
- >{
- > st = (struct st1*)malloc(sizeof(struct st1*));
- > st->name = (char*)malloc(16);
- > strcpy(st->name,"Test");
- > st->yadda = 100;
- >}
- >
- >At the last line of code in fn1, all the values are correct; st->name is
- >"Test" and st->yadda is 100. As soon as it exits, however, st->name
- >points to NULL and st->yadda is zero. The allocation of the structure in
- >the first line of fn1 doesn't seem to matter; both ways, I get NULL
- >pointers coming out of my ears.
- >
-
- the local copy of the pointer is getting alloced and lost in transit.
-
- it will be better to write the function as follows :
-
- #define FAILURE 0
- #define SUCCESS 1
- int fn1(struct st1 **ppst)
- {
- int iRetVal = FAILURE;
- if (*ppst = malloc(sizeof(struct st1)))
- {
- if ((*ppst)->name = (char*)malloc(16))
- {
- (*ppst)strcpy(st->name,"Test");
- (*ppst)->yadda = 100;
- return(SUCCESS);
- }
- free(*ppst);
- *ppst = NULL;
- }
- return (FAILURE);
- }
-
- and in the caller program
-
- struct st1 *pst;
-
- if (FAILURE == fn1(&pst))
- {
- /* something failed in fn1 handle the error
- }
- else
- {
- /* now you can use pst->name and pst->yadda */
- }
-
- Please note that I have not even attempted to compile this code, there may be silly typos
- here and there, but hope you get the idea.
-
- And yes include the header file.
-
- /* --------------------------------------------------------
- MAG@ESKIMO.COM
- http://www.eskimo.com/~mag/index.html
- ***********************************************************
- To understand recursion one must first understand recursion
- ***********************************************************
- -------------------------------------------------------- */
-
-